package com.yanze.controller;

import com.yanze.pojo.BaseJsonResult;
import com.yanze.pojo.SysUser;
import com.yanze.service.UserService;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("mybatis")
public class MyBatisCRUDController {

    @Autowired
    private UserService userService;

    @Autowired
    private Sid sid;

    @RequestMapping("/saveUser")
    public BaseJsonResult saveUser() throws Exception {
        String userId = sid.nextShort();

        SysUser user = new SysUser();
        user.setId(userId);
        user.setUsername("yanze");
        user.setNickname("yanze" + new Date());
        user.setPassword("qwe123");
        user.setIsDelete(0);
        user.setRegistTime(new Date());

        userService.saveUser(user);

        return BaseJsonResult.ok("保存成功！");
    }

    @RequestMapping("/updateUser")
    public BaseJsonResult updateUser() {
        SysUser user = new SysUser();

        user.setId("10011003");
        user.setUsername("updated");
        user.setNickname("updated" + new Date());
        user.setPassword("updated123");
        user.setIsDelete(0);
        user.setRegistTime(new Date());

        userService.updateUser(user);

        return BaseJsonResult.ok("更新成功！");
    }

    @RequestMapping("/deleteUser")
    public BaseJsonResult deleteUser() {
        String userId = "10011003";
        userService.deleteUser(userId);
        return BaseJsonResult.ok("删除成功！");
    }


    //分页查询
    @RequestMapping("/queryUserListPaged")
    public BaseJsonResult quequeryUserListPagedry(Integer page) {
        if (page == null) {
            page = 1;
        }

        int pageSize = 10;

        SysUser user = new SysUser();
        user.setNickname("yanze");
        List<SysUser> userList = userService.queryUserListPaged(user, page, pageSize);

        return BaseJsonResult.ok(userList);
    }

    @RequestMapping("/queryUserByIdCustom")
    public BaseJsonResult queryUserByIdCustom(String userId) {
        return BaseJsonResult.ok(userService.queryUserByIdCustom(userId));
    }

    //事务的回滚
    @RequestMapping("/saveUserTransactional")
    public BaseJsonResult saveUserTransactional() {
        String userId = sid.nextShort();

        SysUser user = new SysUser();
        user.setId(userId);
        user.setUsername("yanze");
        user.setNickname("白泽丶");
        user.setIsDelete(0);
        user.setRegistTime(new Date());
        userService.saveUserTransactional(user);

        return BaseJsonResult.ok("保存成功！");
    }
}
